// 客户端
const prisma = require('./prisma')

// 集合中忽略的数据字段定义查询字段
const omitFields = {
  //
  is_admin: true,
  passwd: true,
  salt: true,
  updated_at: true,
  deleted_at: true,
}

class SysUserModel {
  async create(usr) {
    return await prisma.sysUser.create({
      omit: omitFields,
      data: {
        name: usr.name,
        phone: usr.phone,
        passwd: usr.passwd,
        salt: usr.salt,
        enable: usr.enable,
      },
    })
  }
  //
  async get(id, where = null, useOmit = true) {
    const result = await prisma.sysUser.findFirst({
      where: Object.assign({ id: id }, where),
      // 查找某些字段
      omit: useOmit ? omitFields : {},
    })
    return result
  }

  // 列表 这里官方建议使用游标
  async list(pageNo, pageSize, where = null) {
    //
    const skip = (pageNo - 1) * pageSize
    return await prisma.sysUser.findMany({
      skip: skip,
      take: pageSize,
      orderBy: {
        id: 'desc',
      },
      where: Object.assign({}, where),
      omit: omitFields,
    })
  }

  // 未删除的数据
  async count(where = null) {
    return await prisma.sysUser.count({
      where: Object.assign({}, where),
    })
  }

  // 更新
  async update(id, usr, where = null) {
    // 先判断是
    return await prisma.sysUser.update({
      where: Object.assign({ id: id }, where),
      data: usr,
      omit: omitFields,
    })
  }

  // 删除
  async del(id, where = null) {
    return await prisma.sysUser.update({
      data: {
        deleted_at: new Date(), // 逻辑删除
      },
      where: Object.assign({ id: id }, where),
      omit: omitFields,
    })
  }

  /**
   *
   * @param {*} phone
   * @returns
   */
  async getByPhone(phone) {
    return await prisma.sysUser.findFirst({
      where: {
        phone: phone,
      },
    })
  }

  async loginByPhone(phone) {
    const result = await prisma.sysUser.findFirst({
      where: {
        phone: phone,
      },
    })
    return result
  }
  async login(data) {
    return await prisma.sysUser.findFirst({
      where: {
        phone: data.phone,
        passwd: data.passwd,
      },
      omit: omitFields,
    })
  }
}

module.exports = new SysUserModel()
